import axios,{AxiosResponse} from 'axios'
import Config from '../config'
import {message} from 'antd';
import Nprogress from 'nprogress';
import "nprogress/nprogress.css";

const req = axios.create({
  timeout:10000,
})


// 请求拦截器
req.interceptors.request.use((config:any)=>{
  const token = window.localStorage.getItem("token")
  if(token){
    config.headers['Authori-zation'] = token
  }
  Nprogress.start();
  return config
})


// 响应拦截器
req.interceptors.response.use((response:AxiosResponse<any>)=>{
  Nprogress.done();
  if(response.status === 200){
    if(response.data.success != undefined && !response.data.success){
      message.error(response.data.message || "服务端异常");
      return Promise.reject(response.data)
    }
    return response.data;
  }
  if(response.status === 401){
    window.localStorage.removeItem("token")
    window.location.hash="#/login"
    return
  }
  return Promise.reject(response.data)
},(error:any)=>{
  Nprogress.done();
  if(error.message && error.message.indexOf("timeout of") > -1){
    message.error("链接超时");
    return Promise.resolve({code:500,data:"",msg:"链接超时"})
  }
  console.log(error);
  if(error.response.status === 401){
    window.localStorage.removeItem("token")
    window.location.hash="#/login"
    return Promise.reject(error.response.data)
  }
  return Promise.reject(error.response.data)
})
/**
 * 
 * @param {*} url //请求路径
 * @param {*} method //请求方法
 * @param {*} data //请求数据
 * @param {*} other //额外的信息，包括请求头设置或者是设置content-type
 */


interface requestProps{
  url:string,
  methods:'GET'|'POST'|'PUT'|'DELETE',
  query?:Object,
  data?:Object,
  headers?:Object,
}

class Request{
  constructor(){}
  
  // 构造单例模式，全局只有一个Request 实例!
  static _instance:Request;
  static _getInstance():Request{
    if(this._instance == null){
      this._instance = new Request();
    }
    return this._instance;
  }

  main = async(props:requestProps):Promise<RequestRes>=>{
    const {url,methods,query,data,headers} = props;
    let obj = {
      url:Config.mainHost+url,
      method:methods,
      params:query,
      data:data,
      headers:headers,
    }
    var res =  await req(obj)
    return res as any;
  }

}

export const request = Request._getInstance();


export default Request._getInstance();



interface RequestRes{
  code:200|400|500|401,
  msg?:string
  message?:string,
  data:any
}